package com.honghu.villagepost.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.honghu.villagepost.R
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.BaseActivity
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.constant.Constants
import com.honghu.villagepost.entity.Logistics
import com.honghu.villagepost.entity.WeixinPayEven
import com.honghu.villagepost.util.CopyUtil
import com.honghu.villagepost.util.DateFormatUtil
import com.lzy.okgo.model.Response
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_order_logistics_details.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author: mqwang
 * @create: 2/25/21 2:17 PM
 * @Description: 寄件订单详情
 */
class LogisticsOrderDetailsActivity : BaseActivity() {

    private var orderId: String = ""

    companion object {
        fun self(context: Context, id: String) {
            val intent = Intent(context, LogisticsOrderDetailsActivity::class.java)
            intent.putExtra(Constants.ORDER_ID, id)
            context.startActivity(intent)
        }
    }

    override fun isBindEventBus(): Boolean {
        return true
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_order_logistics_details
    }

    override fun init(savedInstanceState: Bundle?, container: View?) {
        setMainTitle("订单详情")
        orderId = intent.getStringExtra(Constants.ORDER_ID)!!


        tv_pay.setOnClickListener {
            ApiService.logistics_order_pay_wx(this, orderId, object : DialogCallback<LzyResponse<Map<String, String>>>() {
                override fun onSuccess(response: Response<LzyResponse<Map<String, String>>>?) {
                    val api = WXAPIFactory.createWXAPI(mContext, Constants.WEIXIN_APP_ID)
                    val req = PayReq()
                    //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                    //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                    req.appId = response!!.body().data["appid"]
                    req.partnerId = response!!.body().data["partnerid"]
                    req.prepayId = response!!.body().data["prepayid"]
                    req.nonceStr = response!!.body().data["noncestr"]
                    req.timeStamp = response!!.body().data["timestamp"]
                    req.packageValue = response!!.body().data["package"]
                    req.sign = response!!.body().data["sign"]
                    api.sendReq(req)
                }

            })

        }
        tv_cancel.setOnClickListener {
            ApiService.logistics_order_cancel(this, orderId, object : DialogCallback<LzyResponse<Any>>() {
                override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                    getData()
                }
            })
        }

        getData()

    }

    fun getData() {
        ApiService.logistics_order_details(this, orderId, object : DialogCallback<LzyResponse<Logistics>>(this) {
            override fun onSuccess(response: Response<LzyResponse<Logistics>>?) {
                var orderDetails = response!!.body().data

                tv_order_no.setText("订单号：" + orderDetails.logisticsNo)
                tv_order_no.setOnClickListener {
                    CopyUtil.ClipData(mContext, orderDetails.logisticsNo)
                }

                tv_pay_way.setText("付款方式：" + orderDetails.payChannel)
                tv_pay_date.setText("下单时间：" + DateFormatUtil.formatDate(orderDetails.createdTime!!, "yyyy-MM-dd HH:mm:ss"))

                tv_send_name.setText(orderDetails.senderName)
                tv_send_phone.setText(orderDetails.senderMobile)
                tv_send_addr.setText(orderDetails.senderProvince + orderDetails.senderCity + orderDetails.senderDistrict)

                if (!TextUtils.isEmpty(orderDetails.receiverName)) {
                    tv_receiver_name.setText(orderDetails.receiverName)
                }
                if (!TextUtils.isEmpty(orderDetails.receiverMobile)) {
                    tv_receiver_phone.setText(orderDetails.receiverMobile)
                }
                if (!TextUtils.isEmpty(orderDetails.receiverProvince)) {
                    tv_receiver_addr.setText(orderDetails.receiverProvince + orderDetails.receiverCity + orderDetails.receiverDistrict)
                }

                tv_type.setText(orderDetails.goodsInfo)
                if (orderDetails.estimatedWeight != null) {
                    tv_estimated_weight.setText(orderDetails.estimatedWeight.toString())
                }
                tv_total_fee.setText(getString(R.string.price_format, orderDetails.totalFee))
//                tv_order_remark.setText(orderDetails.totalFee)
                tv_total.setText(getString(R.string.price_format, orderDetails.totalFee))

                when (orderDetails!!.state) {
                    //等待买家付款
                    1 -> {
                        tv_status.setText("待揽件")
                    }
                    3 -> {
                        tv_status.setText("已取件")
                    }
                    4 -> {
                        tv_status.setText("待运输")
                    }
                    5 -> {
                        tv_status.setText("运输中")
                    }
                    6 -> {
                        tv_status.setText("到达")
                    }
                    7 -> {
                        tv_status.setText("待派送")
                    }
                    8 -> {
                        tv_status.setText("派送中")
                    }
                    10 -> {
                        tv_status.setText("已签收")
                    }
                    11 -> {
                        tv_status.setText("已取消")
                    }
                }
                //展示支付按钮
                if (orderDetails.state != 11 && orderDetails.payType == 1 && !orderDetails.paid) {
                    layout_bottom.visibility = View.VISIBLE
                    tv_pay.visibility = View.VISIBLE
                    tv_cancel.visibility = View.VISIBLE
                }
                //展示取消按钮
                else if (orderDetails.state == 2) {
                    layout_bottom.visibility = View.VISIBLE
                    tv_pay.visibility = View.GONE
                    tv_cancel.visibility = View.VISIBLE
                } else {
                    layout_bottom.visibility = View.GONE
                }
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun weixinPay(weixinPayEven: WeixinPayEven) {
        setResult(RESULT_OK)
        when (weixinPayEven.code) {
            0 -> {
                showToast("支付成功")
                finish()

            }
            -1 -> showToast("未知错误")
            -2 -> showToast("用户取消")
            else -> {
            }
        }
    }

}